﻿myApp.controller('HomeLoanCalculatorController', function ($scope, $http, ngTableParams, $filter, $templateCache) {
    $scope.$emit('newPageLoaded', {
        'title': 'Home Loan Calculator | ShiJie Property',
        'description': 'Home Loan Calculator. Estimate Your Monthly Repayment Using This Simple To Use Home Loan Calculator. Go Now!',
        'keywords': 'home loan calculator, mortgage calculator, homeloan calculator'
    });

    //$scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 HomeLoan Calculator', 'description': 'Free online home loan calculator. Try it now.' });


    $scope.purchasePrice = 600000;
    $scope.marginFinance = 90;
    $scope.loanAmount = $scope.purchasePrice * $scope.marginFinance / 100;
    $scope.interestRate = 5;
    $scope.tenure = 30;
    $scope.mrta = 0;
    $scope.others = 0;
    $scope.total = $scope.loanAmount + $scope.mrta + $scope.others;

    $scope.calc = false;

    $scope.clearValues = function () {
        $scope.purchasePrice = '';
        $scope.marginFinance = '';
        $scope.loanAmount = '';
        $scope.mrta = '';
        $scope.others = '';
        $scope.total = '';
        $scope.interestRate = '';
        $scope.tenure = '';


    }

    $scope.calculate = function () {

        var purchase_price = $scope.purchasePrice;
        var margin_finance = $scope.marginFinance;
        $scope.loanAmount = purchase_price * margin_finance / 100;

        $scope.total = $scope.loanAmount + $scope.mrta + $scope.others;
        var total_loan_amount = $scope.total;
        $scope.total_months = $scope.tenure * 12;

        var r = $scope.interestRate / (12 * 100);
        var p = (total_loan_amount * r * Math.pow((1 + r), $scope.total_months)) / (Math.pow((1 + r), $scope.total_months) - 1);
        var prin = Math.round(p * 100) / 100;
        $scope.monthlyPayment = prin;
        var mon = Math.round((($scope.total_months * prin) - total_loan_amount) * 100) / 100;
        $scope.totalInterest = mon;
        var tot = Math.round((mon / $scope.total_months) * 100) / 100;

        $scope.monthlyInterest = tot;
        $scope.totalPayment = Math.round(prin * $scope.total_months);

        //alert($scope.monthlyInterest);
        //alert($scope.totalPayment);
       // alert($scope.purchasePrice);


       // alert("Calculated!");

    }


    $scope.numberFormat = function (n) {
        return n.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
    }

    $scope.calculateOnly = function () {
        $scope.calculate();
    }

    $scope.generateTable = function () {
        // $scope.calculate();
        //$scope.calc = true;
        //var total_months = $("#txtTenure").val() * 12;
        //var total_payment = $("#txtTotalPayment").val();
        //var monthly_payment = $("#txtMonthlyPayment").val();
        //var monthly_interest = $("#txtMonthlyIntest").val();
        //var total_loan_amount = $("#txtTotal").val();
        var monthly_principle = $scope.monthlyPayment - $scope.monthlyInterest;
        var loan_balance = $scope.totalPayment;
        var monthly_principle_balance = $scope.total;

        //$scope.payments = [];

        //for (var i = 1; i <= $scope.total_months; i++) {
        //    loan_balance = loan_balance - $scope.monthlyPayment;
        //    monthly_principle_balance = monthly_principle_balance - monthly_principle;
        //    $scope.payments[i] = {
        //        month: i,
        //        loan_balance: loan_balance,
        //        monthly_principle_balance: monthly_principle_balance,
        //        monthly_interest: $scope.monthlyInterest
        //    };
        //}

        var entirePayments = [];
        entirePayments[0] = [{ text: 'Month', bold: true, fontSize: 12 }, { text: 'Loan Balance(RM)', bold: true, fontSize: 12 }, { text: 'Monthly Principle Balance(RM)', bold: true, fontSize: 12 }, { text: 'Monthly Interest(RM)', bold: true, fontSize: 12 }];

        for (var i = 1; i <= $scope.total_months; i++) {
            loan_balance = loan_balance - $scope.monthlyPayment;
            monthly_principle_balance = monthly_principle_balance - monthly_principle;
            entirePayments[i] = [
                $scope.numberFormat(i).toString(),
                $scope.numberFormat(loan_balance).toString(),
                $scope.numberFormat(monthly_principle_balance).toString(),
                $scope.numberFormat($scope.monthlyInterest).toString()
            ]
        }
        //console.log(JSON.stringify(entirePayments));



        var docDefinition = {
            content: [
              {
                  table: {
                      // headers are automatically repeated if the table spans over multiple pages
                      // you can declare how many rows should be treated as headers
                      headerRows: 1,
                      widths: [55, '*','*', '*'],

                      body: entirePayments

                  }
              }
            ]
        };
        pdfMake.createPdf(docDefinition).open();

      

    }

    //$scope.totalItems = 365;
    //$scope.currentPage = 1;
    //$scope.numPerPage = 100;


    //$scope.paginate = function (value) {
    //    var begin, end, index;
    //    begin = ($scope.currentPage - 1) * $scope.numPerPage;
    //    end = begin + $scope.numPerPage;
    //    index = $scope.objects.indexOf(value);
    //    return (begin <= index && index < end);
    //};


    function pageInit() {
        $scope.calculate();
    }
    pageInit();


});